<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTree, ElCheckboxGroup, ElCheckbox } from 'element-plus'
import { getMenuListApi, searchRoleApi } from '@/api/menu'
import { filter, eachTree } from '@/utils/tree'

const { t } = useI18n()

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const formSchema = ref<FormSchema[]>([
  {
    field: 'name',
    label: t('role.roleName'),
    component: 'Input'
  },
  {
    field: 'englishName',
    label: t('role.englishName'),
    component: 'Input'
  },

  {
    field: 'isEnabled',
    label: t('menu.status'),
    value: 1,
    component: 'Select',
    componentProps: {
      options: [
        {
          label: t('userDemo.disable'),
          value: 0
        },
        {
          label: t('userDemo.enable'),
          value: 1
        }
      ]
    }
  },
  {
    field: 'remark',
    label: t('common.remark'),
    component: 'Input'
  },
  {
    field: 'menu',
    label: t('role.menu'),
    // colProps: {
    //   span: 24
    // },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              {/*   check-strictly */}
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="guid"
                    highlight-current
                    default-expand-all
                    data={treeData.value}
                    onNode-click={nodeClick}
                  >
                    {{
                      default: (data) => {
                        return <span>{data.data.name}</span>
                      }
                    }}
                  </ElTree>
                </div>
                <div class="flex-1">
                  {unref(currentTreeData) && unref(currentTreeData)?.permissionList ? (
                    <ElCheckboxGroup v-model={unref(currentTreeData).meta.permission}>
                      {unref(currentTreeData)?.permissionList.map((v: any) => {
                        return <ElCheckbox label={v.value}>{v.label}</ElCheckbox>
                      })}
                    </ElCheckboxGroup>
                  ) : null}
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

const currentTreeData = ref()
const nodeClick = (treeData: any) => {
  console.log('------', treeData)
  currentTreeData.value = treeData
}

const rules = reactive({
  name: [required()]
  // englishName: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref<menuDt[]>([])
const getMenuList = async () => {
  const res = await getMenuListApi()
  if (res) {
    treeData.value = res.data //.list
    if (!props.currentRow) return
    await nextTick()

    const checked: any[] = []
    eachTree(props.currentRow.permissionList, (v) => {
      checked.push({
        guid: v //.guid,
        // permission: v.meta?.permission || []
      })
    })
    // eachTree(treeData.value, (v) => {
    //   const index = findIndex(checked, (item) => {
    //     return item.guid === v.guid
    //   })
    //   if (index > -1) {
    //     const meta = { ...(v.meta || {}) }
    //     meta.permission = checked[index].permission
    //     v.meta = meta
    //   }
    // })

    for (const item of checked) {
      unref(treeRef)?.setChecked(item.guid, true, false)
    }
  }
}
getMenuList()
interface menuDt {
  guid: string
  parentGuid?: string
  children?: menuDt[]
}

const findParent = (nodes, guid, parentIdKey = 'parentGuid', idKey = 'guid') => {
  for (let i = 0; i < nodes.length; i++) {
    if (nodes[i][idKey] === guid) {
      return nodes[i]
    }
    if (nodes[i].children && nodes[i].children.length > 0) {
      const parent = findParent(nodes[i].children, guid, parentIdKey, idKey)
      if (parent) {
        return parent
      }
    }
  }
  return null
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    let checkedKeys = unref(treeRef)?.getCheckedKeys() || []
    let arr = new Set()
    checkedKeys.map((guid) => {
      // console.log('-----', findParent(treeData.value, guid).parentGuid)
      let parentGuid = findParent(treeData.value, guid).parentGuid
      if (parentGuid) {
        arr.add(parentGuid)
        // let index = checkedKeys.findIndex((id) => id != parentGuid)
        // console.log('没有包含------', index, parentGuid)
        // if (index < 0) {
        //   noHaveGuid = parentGuid
        //   console.log('没有包含------', parentGuid)
        // }
      }
    })
    checkedKeys.map((item) => {
      arr.add(item)
    })

    // const data = filter(unref(treeData), (item: any) => {
    //   return checkedKeys.includes(item.guid)
    // })
    formData.menus = [...arr] || []
    console.log(formData)
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
